﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace Medianamik.Core
{
    public class ObjectBuilder
    {
        public string TypeName
        {
            get;
            private set;
        }
        public object[] Params
        {
            get;
            private set;
        }

        public ObjectBuilder(string pTypeName, params object[] pParams)
        {
            TypeName = pTypeName;
            Params = pParams;
        }
        public T GetInstance<T>()
        {
            // Find the class
            System.Type type = System.Type.GetType(TypeName);

            if (type == null) { throw new CoreException("Cannot create an instance of " + TypeName + ". Be sure to use the AssemblyQualifiedName"); }

            Type[] typeArray = Params.Select(p => p.GetType()).ToArray();

            // Get it's constructor
            ConstructorInfo constructor = type.GetConstructor(typeArray);

            // Invoke it's constructor, which returns an instance.
            T createdObject = (T)constructor.Invoke(Params);

            // Pass back the instance
            return createdObject;
        }
        public object GetInstance()
        {
            return GetInstance<object>();
        }
    }
}
